package com.roin.learn.freemarker.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * 文件上传<br>
 * 
 * @author 罗毅
 * @version 1.0,2017年6月1日 上午9:11:39
 * @since learn-springmvc 0.0.1
 */
@Controller
@RequestMapping("file")
public class FileUploadController {
	// 跳到文件上传页面
	@RequestMapping("upload.htm")
	public String toFileUpload() {
		return "file/upload";
	}

	/***
	 * 单个文件上传 用@RequestParam注解来指定表单上的file为MultipartFile
	 * 
	 * @param file
	 * @return
	 */
	@RequestMapping("upload.do")
	public String fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		// 判断文件是否为空
		saveFile(file, request);
		// 重定向
		return "redirect:list.htm";
	}

	/***
	 * 多文件上传 用@RequestParam注解来指定表单上的file为MultipartFile
	 * 
	 * @param file
	 * @return
	 */
	@RequestMapping("multiUpload.do")
	public String multiUpload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
		// 判断file数组不能为空并且长度大于0
		if (files != null && files.length > 0) {
			// 循环获取file数组中得文件
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				// 保存文件
				saveFile(file, request);
			}
		}
		// 重定向
		return "redirect:list.htm";
	}

	/***
	 * 保存文件
	 * 
	 * @param file
	 * @return
	 */
	private boolean saveFile(MultipartFile file, HttpServletRequest request) {
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				// 文件保存路径
				String filePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload/"
						+ file.getOriginalFilename();
				// 转存文件
				file.transferTo(new File(filePath));
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/***
	 * 读取上传文件中得所有文件并返回
	 * 
	 * @return
	 */
	@RequestMapping("list.htm")
	public ModelAndView list(HttpServletRequest request) {
		String filePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload/";
		ModelAndView mav = new ModelAndView("file/list");
		File uploadDest = new File(filePath);
		String[] fileNames = uploadDest.list();
		mav.addObject("fileNames", fileNames);
		return mav;
	}
}
